<template>
  <section>
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="text-center mb-20">
        <div v-if="badgeText" class="inline-flex items-center px-4 py-2 rounded-full bg-gradient-to-r from-blue-50 to-purple-50   border border-blue-200/50  mb-6">
          <div class="w-2 h-2 bg-blue-500 rounded-full mr-2 animate-pulse"></div>
          <span class="text-sm font-bold text-gray-700  tracking-wide">{{ badgeText }}</span>
        </div>
        <h2 class="text-2xl md:text-3xl font-bold text-gray-900  mb-3">
          {{ title }}
          <span v-if="titleHighlight" class="bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent font-black tracking-wide">{{ titleHighlight }}</span>
        </h2>
        <p v-if="description" class="text-base text-gray-600  max-w-xl mx-auto">
          {{ description }}
        </p>
      </div>

      <!-- Enhanced Agents Grid -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-16">
        <div 
          v-for="agent in agents" 
          :key="agent.id"
          @click="navigateToAgent(agent.id)"
          class="group bg-white  rounded-2xl border border-gray-200/50  p-6 hover:shadow-2xl transition-all duration-500 hover:border-blue-200/50  hover:-translate-y-2 cursor-pointer"
        >
          <!-- Agent header with category badge -->
          <div class="flex items-start justify-between mb-4">
            <div class="flex items-center space-x-3">
              <!-- Category badge -->
              <span class="px-2 py-1 bg-blue-100  text-blue-800  rounded-full text-xs font-semibold">
                {{ formatCategory(agent.category) }}
              </span>
              <!-- Agent icon with online indicator -->
              <div class="relative">
                <div class="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center text-white text-lg shadow-lg group-hover:scale-110 transition-transform duration-300">
                  {{ agent.metadata.logo }}
                </div>
                <div class="absolute -bottom-1 -right-1 w-4 h-4 bg-green-500 rounded-full border-2 border-white "></div>
              </div>
            </div>
            <!-- Favorite button -->
            <button class="p-2 text-gray-400  hover:text-red-500 transition-colors duration-200">
              <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
              </svg>
            </button>
          </div>

          <!-- Agent name and role -->
          <div class="mb-3">
            <h3 class="font-bold text-gray-900  text-lg mb-1 line-clamp-1">{{ agent.name }}</h3>
            <p class="text-sm text-gray-500 ">{{ getAgentRole(agent.category) }}</p>
          </div>

          <!-- Rating and usage -->
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center space-x-2">
              <div class="flex">
                <svg v-for="i in 5" :key="i" class="w-4 h-4" :class="i <= Math.floor(agent.metadata.rating) ? 'text-yellow-400' : 'text-gray-300'" fill="currentColor" viewBox="0 0 20 20">
                  <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                </svg>
              </div>
              <span class="text-sm font-semibold text-gray-700">{{ agent.metadata.rating }}</span>
              <span class="text-sm text-gray-500">{{ formatNumber(agent.metadata.usageCount) }}</span>
            </div>
          </div>

          <!-- Agent description -->
          <p class="text-gray-600 mb-4 line-clamp-2 leading-relaxed text-sm">
            {{ agent.description }}
          </p>

          <!-- Skills/Tags -->
          <div class="flex flex-wrap gap-2 mb-4">
            <span 
              v-for="(skill, index) in getAgentSkills(agent.category).slice(0, 2)" 
              :key="index"
              class="px-3 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-medium"
            >
              {{ skill }}
            </span>
            <span 
              v-if="getAgentSkills(agent.category).length > 2"
              class="px-3 py-1 bg-purple-100 text-purple-700 rounded-full text-xs font-medium"
            >
              +{{ getAgentSkills(agent.category).length - 2 }}
            </span>
          </div>

          <!-- Pricing and action -->
          <div class="flex items-center justify-between">
            <div>
              <div class="text-lg font-bold text-gray-900 ">
                {{ agent.pricing.model === 'free' ? 'Free' : `$${agent.pricing.price || 150}` }}
              </div>
              <div class="text-xs text-gray-500 ">
                {{ agent.pricing.model === 'free' ? 'Per Use' : 'Per Hour' }}
              </div>
            </div>
            <button 
              @click.stop="useAgent(agent.id)"
              class="px-6 py-2 bg-blue-600  text-white rounded-lg font-semibold hover:bg-blue-700  transition-colors duration-200 text-sm"
            >
              Use
            </button>
          </div>
        </div>
      </div>

      <!-- Enhanced View all button -->
      <div v-if="showViewAll" class="text-center">
        <router-link 
          to="/marketplace" 
          class="group inline-flex items-center px-8 py-4 bg-gradient-to-r from-blue-600 to-purple-600   text-white rounded-2xl font-semibold hover:from-blue-700 hover:to-purple-700   transition-all duration-300 shadow-xl hover:shadow-2xl transform hover:-translate-y-1"
        >
          <span class="font-bold tracking-wide">Explore All Agents</span>
          <svg class="ml-3 w-5 h-5 group-hover:translate-x-1 transition-transform duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3" />
          </svg>
        </router-link>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router'
  import type { Agent } from '../../types'

  const router = useRouter()

  // Props
  interface Props {
    agents: Agent[]
    badgeText?: string
    title: string
    titleHighlight?: string
    description?: string
    showViewAll?: boolean
  }

  const props = withDefaults(defineProps<Props>(), {
    showViewAll: false
  })

  // Methods
  const formatNumber = (num: number) => {
    if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k'
    }
    return num.toString()
  }

  const formatCategory = (category: string) => {
    return category.split('-').map(word =>
      word.charAt(0).toUpperCase() + word.slice(1)
    ).join(' ')
  }

  const getAgentRole = (category: string) => {
    const roleMap: Record<string, string> = {
      'coding': 'Software Engineer',
      'agentic-framework': 'AI Architect',
      'chatbot-builder': 'Conversation Designer',
      'low-code-builder': 'Automation Specialist',
      'digital-worker': 'Virtual Assistant',
      'writing': 'Content Creator',
      'analysis': 'Data Analyst',
      'automation': 'Process Engineer',
      'creative': 'Creative Director'
    }
    return roleMap[category] || 'AI Specialist'
  }

  const getAgentSkills = (category: string) => {
    const skillsMap: Record<string, string[]> = {
      'coding': ['Code Generation', 'Debugging', 'Code Review'],
      'agentic-framework': ['Multi-Agent Systems', 'Workflow Design', 'API Integration'],
      'chatbot-builder': ['Natural Language', 'Conversation Flow', 'Intent Recognition'],
      'low-code-builder': ['Process Automation', 'Workflow Design', 'Integration'],
      'digital-worker': ['Task Automation', 'Data Processing', 'Customer Service'],
      'writing': ['Content Creation', 'SEO Optimization', 'Copywriting'],
      'analysis': ['Data Analysis', 'Trend Prediction', 'Reporting'],
      'automation': ['Process Optimization', 'Workflow Design', 'System Integration'],
      'creative': ['Design Thinking', 'Creative Strategy', 'Brand Development']
    }
    return skillsMap[category] || ['AI Automation', 'Process Optimization']
  }

  // Navigation methods
  const navigateToAgent = (agentId: string) => {
    // Prevent any form submission or focus issues
    event?.preventDefault()
    event?.stopPropagation()

    // Use setTimeout to ensure the click event is fully processed
    setTimeout(() => {
      router.push(`/agent/${agentId}`)
    }, 0)
  }

  const useAgent = (agentId: string) => {
    // In real app, this would handle agent usage logic
    console.log('Using agent:', agentId)
    // For now, also navigate to detail page
    router.push(`/agent/${agentId}`)
  }
</script>

<style scoped>
  .line-clamp-1 {
    display: -webkit-box;
    -webkit-line-clamp: 1;
    line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
</style>
